<template>
  <div>
    <el-form :model="form" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="市区">
        <el-input v-model="form.city"></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="form.address"></el-input>
      </el-form-item>
    </el-form>
    <el-button @click="submit" type="primary">提交</el-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      id: "",
      form: {
        name: "",
        city: "",
        address: ""
      },
    }
  },
  methods: {
    async submit() {
      if (!!this.form.name && !!this.form.city && !!this.form.address) {
          const res = this.id ? await this.$http.put(`/user/${this.id}`,this.form) : await this.$http.post("/user",this.form);
          if (res.data.success) {
            this.id ? this.$message({ type:"success", message: "修改成功" }) : this.$message({ type:"success", message: "添加成功" });
            this.$router.push("/user");
          }
          else {
            this.id ? this.$message.error("修改失败，请稍后重试") : this.$message.error("添加失败，请稍后重试");
          }
      }
      else {
        this.$message({ type: "warning", message:"存在必填项未输入" });
      }
    }
  },
  async created() {
    this.id = this.$route.params.id || undefined;
    if(this.id) {
      const res = await this.$http.get(`/user/${this.id}`);
      this.form = res.data.data;
    }
  }
}
</script>